<template>
	<view class="appointment-container">
    <!-- 填充区 -->
    <view class="statusBar" :style="{ height: getStatusBarHeight()+ 'px'}"></view>
		<view class="step-container">
			<!-- 步骤指示器 -->
			<view class="steps">
				<view class="step" :class="{ active: currentStep >= 1 }">
					<view class="step-number">1</view>
					<text>选择接种点</text>
				</view>
				<view class="step-line" :class="{ active: currentStep >= 2 }"></view>
				<view class="step" :class="{ active: currentStep >= 2 }">
					<view class="step-number">2</view>
					<text>选择疫苗</text>
				</view>
				<view class="step-line" :class="{ active: currentStep >= 3 }"></view>
				<view class="step" :class="{ active: currentStep >= 3 }">
					<view class="step-number">3</view>
					<text>选择时间</text>
				</view>
			</view>
			
			<!-- 步骤1：选择接种点 -->
			<view class="step-content" v-if="currentStep === 1">
				<view class="site-list">
					<view 
						class="site-item" 
						v-for="(site, index) in sites" 
						:key="index"
						:class="{ active: selectedSite === site }"
						@tap="selectSite(site)"
					>
						<view class="site-info">
							<text class="site-name">{{site.name}}</text>
							<text class="site-address">{{site.address}}</text>
							<view class="site-stats">
								<text>剩余疫苗: {{site.vaccineCount}}剂</text>
								<!-- <text>{{site.distance}}km</text> -->
							</view>
						</view>
						<uni-icons v-if="selectedSite === site" type="checkmarkempty" size="24" color="#007AFF"></uni-icons>
					</view>
				</view>
			</view>
			
			<!-- 步骤2：选择疫苗 -->
			<view class="step-content" v-if="currentStep === 2">
				<view class="vaccine-list">
					<view 
						class="vaccine-item" 
						v-for="(vaccine, index) in vaccines" 
						:key="index"
						:class="{ active: selectedVaccine === vaccine }"
						@tap="selectVaccine(vaccine)"
					>
						<view class="vaccine-info">
							<text class="vaccine-name">{{vaccine.name}}</text>
							<text class="vaccine-desc">{{vaccine.manufacturer}}</text>
							<text class="vaccine-stock">库存: {{vaccine.stock}}剂</text>
						</view>
						<uni-icons v-if="selectedVaccine === vaccine" type="checkmarkempty" size="24" color="#007AFF"></uni-icons>
					</view>
				</view>
			</view>
			
			<!-- 步骤3：选择时间 -->
			<view class="step-content" v-if="currentStep === 3">
				<view class="calendar-container">
					<uni-calendar 
						:insert="true"
						:start-date="startDate"
						:end-date="endDate"
						@change="dateChange"
					/>
				</view>
				<view class="time-slots" v-if="selectedDate">
					<text class="time-slots-title">可预约时段</text>
					<view class="time-grid">
						<view 
							class="time-item" 
							v-for="(time, index) in timeSlots" 
							:key="index"
							:class="{ 
								active: selectedTime === time,
								disabled: time.available === 0
							}"
							@tap="selectTimeSlot(time)"
						>
							<text>{{time.time}}</text>
							<text class="available-count">剩余{{time.available}}个</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<button 
				class="prev-btn" 
				v-if="currentStep > 1" 
				@tap="prevStep"
			>上一步</button>
			<button 
				class="next-btn" 
				:disabled="!canProceed"
				@tap="nextStep"
			>{{currentStep === 3 ? '确认预约' : '下一步'}}</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getStatusBarHeight, getBottomSafeHeight } from '@/utils/system'
import { getVaccineInfoAPI,submitAppointmentAPI } from '@/services/vaccine'
import { onLoad, onShow } from '@dcloudio/uni-app'

const currentStep = ref(1)
const selectedSite = ref(null)
const selectedVaccine = ref(null)
const selectedDate = ref('')
const selectedTime = ref(null)

// 接种点信息
const sites = ref([])
const getSites = async () => {
	const res = await getVaccineInfoAPI()
	const selectedSiteId = uni.getStorageSync('selectedSiteId')
	console.log('接种点信息',res)
	if (selectedSiteId) {
    // 如果有选中的接种点ID，只显示该接种点
    sites.value = res.data.filter(site => site.id === selectedSiteId)
    // 使用完后清除storage
    uni.removeStorageSync('selectedSiteId')
	} else {
		// 否则显示所有可预约的接种点
		sites.value = res.data.filter(site => site.status === '可预约')
	}
}
onShow(() => {
	getSites()
})

// 疫苗信息
const vaccines = ref([
	{
		name: '新冠疫苗',
		manufacturer: '科兴生物',
		stock: 100
	},
	{
		name: '新冠疫苗',
		manufacturer: '国药集团',
		stock: 80
	}
])

const timeSlots = ref([
	{ time: '09:00', available: 5 },
	{ time: '09:30', available: 3 },
	{ time: '10:00', available: 0 },
	{ time: '10:30', available: 4 },
	{ time: '11:00', available: 2 },
	{ time: '14:00', available: 6 },
	{ time: '14:30', available: 3 },
	{ time: '15:00', available: 4 },
	{ time: '15:30', available: 0 },
	{ time: '16:00', available: 5 }
])

const startDate = computed(() => {
	const date = new Date()
	return date.toISOString().split('T')[0]
})

const endDate = computed(() => {       
	const date = new Date()
	date.setDate(date.getDate() + 14)
	return date.toISOString().split('T')[0]
})

const canProceed = computed(() => {
	switch (currentStep.value) {
		case 1:
			return selectedSite.value !== null
		case 2:
			return selectedVaccine.value !== null
		case 3:
			return selectedDate.value && selectedTime.value !== null
		default:
			return false
	}
})

onMounted(() => {
	const query = uni.getLaunchOptionsSync().query
	if (query.site) {
		selectedSite.value = JSON.parse(decodeURIComponent(query.site))
		currentStep.value = 2
	}
})

const selectSite = (site) => {
	selectedSite.value = site
}

const selectVaccine = (vaccine) => {
	selectedVaccine.value = vaccine
}

const dateChange = (e) => {
	selectedDate.value = e.fulldate
	selectedTime.value = null
}

const selectTimeSlot = (time) => {
	if (time.available === 0) return
	selectedTime.value = time
}

const prevStep = () => {
	if (currentStep.value > 1) {
		currentStep.value--
	}
}

const nextStep = () => {
	if (!canProceed.value) return
	
	if (currentStep.value < 3) {
		currentStep.value++
	} else {
		submitAppointment()
	}
}

//提交预约
const submitAppointment = async () => {
	const appointmentData = {
		site: selectedSite.value,
		vaccine: selectedVaccine.value,
		date: selectedDate.value,
		time: selectedTime.value
	}
	console.log('预约数据',appointmentData)
	try {
		uni.showLoading({
			title: '提交预约...'
		})
		const res = await submitAppointmentAPI(appointmentData)
		console.log('预约结果',res)
		setTimeout(() => {
			uni.hideLoading()
			uni.showToast({
				title: '预约成功',
				icon: 'success',
				duration: 2000,
				success: () => {
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/my-appointments/my-appointments'
						})
					}, 2000)
				}
			})
		}, 1500)
	} catch (error) {
		console.log('预约失败',error)
	}
}
</script>

<style lang="scss">
.appointment-container {
	min-height: 100vh;
	background-color: $uni-bg-color-grey;
	padding-bottom: 120rpx;
  .statusBar{
    width: 100%;
    background-color: $uni-bg-color;
    border-bottom: 2rpx solid $uni-bg-color-grey;
  }
	
	.step-container {
		background-color: $uni-bg-color;
		padding: 40rpx 20rpx;
		
		.steps {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 40rpx;
			padding-bottom: 50rpx;
      border-bottom: 2rpx solid $uni-bg-color-grey;
			
			.step {
				display: flex;
				flex-direction: column;
				align-items: center;
				
				.step-number {
					width: 60rpx;
					height: 60rpx;
					border-radius: 30rpx;
					background-color: #DDDDDD;
					color: $uni-bg-color;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 20rpx;
				}
				
				text {
					font-size: 24rpx;
					color: #666666;
				}
				
				&.active {
					.step-number {
						background-color: #007AFF;
					}
					
					text {
						color: #007AFF;
					}
				}
			}
			
			.step-line {
				flex: 1;
				height: 2rpx;
				background-color: #DDDDDD;
				margin: 0 20rpx;
				margin-bottom: 40rpx;
				
				&.active {
					background-color: #007AFF;
				}
			}
		}
		
		.step-content {
			padding: 20rpx;
			
			.site-list, .vaccine-list {
				background-color: $uni-bg-color;
				
				.site-item, .vaccine-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 30rpx;
					border-bottom: 1rpx solid #EEEEEE;
					
					&.active {
						background-color: #F0F7FF;
					}
					
					.site-name, .vaccine-name {
						font-size: 32rpx;
						font-weight: bold;
						color: #333333;
						margin-bottom: 10rpx;
						display: block;
					}
					
					.site-address, .vaccine-desc {
						font-size: 26rpx;
						color: #666666;
						margin-bottom: 10rpx;
						display: block;
					}
					
					.site-stats, .vaccine-stock {
						font-size: 24rpx;
						color: #999999;
					}
				}
			}
			
			.calendar-container {
				background-color: $uni-bg-color;
				padding: 20rpx;
				margin-bottom: 20rpx;
			}
			
			.time-slots {
				background-color: $uni-bg-color;
				padding: 20rpx;
				
				.time-slots-title {
					font-size: 28rpx;
					color: #333333;
					margin-bottom: 20rpx;
					display: block;
				}
				
				.time-grid {
					display: grid;
					grid-template-columns: repeat(3, 1fr);
					gap: 20rpx;
					
					.time-item {
						background-color: $uni-bg-color-grey;
						padding: 20rpx;
						border-radius: 10rpx;
						text-align: center;
						
						text {
							font-size: 28rpx;
							color: #333333;
							display: block;
							
							&.available-count {
								font-size: 24rpx;
								color: #999999;
								margin-top: 10rpx;
							}
						}
						
						&.active {
							background-color: #007AFF;
							
							text {
								color: $uni-bg-color;
							}
						}
						
						&.disabled {
							background-color: #EEEEEE;
							opacity: 0.5;
						}
					}
				}
			}
		}
	}
	
	.bottom-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		background-color: $uni-bg-color;
		display: flex;
		justify-content: space-between;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		// #ifdef H5
		bottom: 94rpx; /* tab栏高度一般是50px = 100rpx */
		// #endif
		
		.prev-btn, .next-btn {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 40rpx;
			font-size: 28rpx;
		}
		
		.prev-btn {
			margin-right: 20rpx;
			background-color: $uni-bg-color-grey;
			color: #666666;
		}
		
		.next-btn {
			background-color: #007AFF;
			color: $uni-bg-color;
			
			&[disabled] {
				background-color: #CCCCCC;
				color: $uni-bg-color;
			}
		}
	}
}
</style> 